<?php
use think\facade\Db;
include(ROOT_PATH.'basic/common.php');

/**
 * @param $arr
 * @param $key_name
 * @return array
 * 将数据库中查出的列表以指定的 id 作为数组的键名
 */
function convert_arr_key($arr, $key_name)
{
    $arr2 = array();
    foreach($arr as $key => $val){
        $arr2[$val[$key_name]] = $val;
    }
    return $arr2;
}

function encrypt($str){
    return md5($str);
}

/**
 * 获取数组中的某一列
 * @param array $arr 数组
 * @param string $key_name  列名
 * @return array  返回那一列的数组
 */
function get_arr_column($arr, $key_name)
{
    $arr2 = array();
    foreach($arr as $key => $val){
        $arr2[] = $val[$key_name];
    }
    return $arr2;
}


/**
 * 获取url 中的各个参数  类似于 pay_code=alipay&bank_code=ICBC-DEBIT
 * @param type $str
 * @return type
 */
function parse_url_param($str){
    $data = array();
    $str = explode('?',$str);
    $str = end($str);
    $parameter = explode('&',$str);
    foreach($parameter as $val){
        $tmp = explode('=',$val);
        $data[$tmp[0]] = $tmp[1];
    }
    return $data;
}


/**
 * 二维数组排序
 * @param $arr
 * @param $keys
 * @param string $type
 * @return array
 */
function array_sort($arr, $keys, $type = 'desc')
{
    $key_value = $new_array = array();
    foreach ($arr as $k => $v) {
        $key_value[$k] = $v[$keys];
    }
    if ($type == 'asc') {
        asort($key_value);
    } else {
        arsort($key_value);
    }
    reset($key_value);
    foreach ($key_value as $k => $v) {
        $new_array[$k] = $arr[$k];
    }
    return $new_array;
}


/**
 * 多维数组转化为一维数组
 * @param 多维数组
 * @return array 一维数组
 */
function array_multi2single($array)
{
    static $result_array = array();
    foreach ($array as $value) {
        if (is_array($value)) {
            array_multi2single($value);
        } else
            $result_array [] = $value;
    }
    return $result_array;
}

/**
 * 友好时间显示
 * @param $time
 * @return bool|string
 */
function friend_date($time)
{
    if (!$time)
        return false;
    $fdate = '';
    $d = time() - intval($time);
    $ld = $time - mktime(0, 0, 0, 0, 0, date('Y')); //得出年
    $md = $time - mktime(0, 0, 0, date('m'), 0, date('Y')); //得出月
    $byd = $time - mktime(0, 0, 0, date('m'), date('d') - 2, date('Y')); //前天
    $yd = $time - mktime(0, 0, 0, date('m'), date('d') - 1, date('Y')); //昨天
    $dd = $time - mktime(0, 0, 0, date('m'), date('d'), date('Y')); //今天
    $td = $time - mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')); //明天
    $atd = $time - mktime(0, 0, 0, date('m'), date('d') + 2, date('Y')); //后天
    if ($d == 0) {
        $fdate = '刚刚';
    } else {
        switch ($d) {
            case $d < $atd:
                $fdate = date('Y年m月d日', $time);
                break;
            case $d < $td:
                $fdate = '后天' . date('H:i', $time);
                break;
            case $d < 0:
                $fdate = '明天' . date('H:i', $time);
                break;
            case $d < 60:
                $fdate = $d . '秒前';
                break;
            case $d < 3600:
                $fdate = floor($d / 60) . '分钟前';
                break;
            case $d < $dd:
                $fdate = floor($d / 3600) . '小时前';
                break;
            case $d < $yd:
                $fdate = '昨天' . date('H:i', $time);
                break;
            case $d < $byd:
                $fdate = '前天' . date('H:i', $time);
                break;
            case $d < $md:
                $fdate = date('m月d日 H:i', $time);
                break;
            case $d < $ld:
                $fdate = date('m月d日', $time);
                break;
            default:
                $fdate = date('Y年m月d日', $time);
                break;
        }
    }
    return $fdate;
}


// 递归删除文件夹
function delFile($path,$delDir = FALSE) {
    if(!is_dir($path))
        return FALSE;
    $handle = @opendir($path);
    if ($handle) {
        while (false !== ( $item = readdir($handle) )) {
            if ($item != "." && $item != "..")
                is_dir("$path/$item") ? delFile("$path/$item", $delDir) : unlink("$path/$item");
        }
        closedir($handle);
        if ($delDir) return rmdir($path);
    }else {
        if (file_exists($path)) {
            return unlink($path);
        } else {
            return FALSE;
        }
    }
}


/**
 * 多个数组的笛卡尔积
 *
 * @param unknown_type $data
 */
function combineDika() {
    $data = func_get_args();
    $data = current($data);
    $result = array();
    $arr1 = array_shift($data);
    foreach($arr1 as $key=>$item)
    {
        $result[] = array($item);
    }

    foreach($data as $key=>$item)
    {
        $result = combineArray($result,$item);
    }
    return $result;
}


/**
 * 两个数组的笛卡尔积
 * @param unknown_type $arr1
 * @param unknown_type $arr2
 */
function combineArray($arr1,$arr2) {
    $result = array();
    foreach ($arr1 as $item1)
    {
        foreach ($arr2 as $item2)
        {
            $temp = $item1;
            $temp[] = $item2;
            $result[] = $temp;
        }
    }
    return $result;
}
/**
 * 将二维数组以元素的某个值作为键 并归类数组
 * array( array('name'=>'aa','type'=>'pay'), array('name'=>'cc','type'=>'pay') )
 * array('pay'=>array( array('name'=>'aa','type'=>'pay') , array('name'=>'cc','type'=>'pay') ))
 * @param $arr 数组
 * @param $key 分组值的key
 * @return array
 */
function group_same_key($arr,$key){
    $new_arr = array();
    foreach($arr as $k=>$v ){
        $new_arr[$v[$key]][] = $v;
    }
    return $new_arr;
}

/**
 * 获取随机字符串
 * @param int $randLength  长度
 * @param int $addtime  是否加入当前时间戳
 * @param int $includenumber   是否包含数字
 * @return string
 */
function get_rand_str($randLength=6,$addtime=1,$includenumber=0){
    if ($includenumber){
        $chars='abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQEST123456789';
    }else {
        $chars='abcdefghijklmnopqrstuvwxyz';
    }
    $len=strlen($chars);
    $randStr='';
    for ($i=0;$i<$randLength;$i++){
        $randStr.=$chars[rand(0,$len-1)];
    }
    $tokenvalue=$randStr;
    if ($addtime){
        $tokenvalue=$randStr.time();
    }
    return $tokenvalue;
}

//提交 GET URL
function curlGet($url, $data = '', $method = 'GET'){
    $ch = curl_init();
    $header = ["Accept-Charset"=>"utf-8"];
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $temp = curl_exec($ch);
    return $temp;
}

/**
 * CURL请求
 * @param $url string 请求url地址
 * @param $method string 请求方法 get post
 * @param mixed $postfields post数据数组
 * @param array $headers 请求header信息
 * @param bool|false $debug  调试开启 默认false
 * @return mixed
 */
function httpRequest($url, $method="GET", $postfields = null, $headers = array(), $debug = false)
{
    $method = strtoupper($method);
    $ci = curl_init();
    /* Curl settings */
    curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
    curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
    curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); /* 在发起连接前等待的时间，如果设置为0，则无限等待 */
    curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 设置cURL允许执行的最长秒数 */
    curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
    switch ($method) {
        case "POST":
            curl_setopt($ci, CURLOPT_POST, true);
            if (!empty($postfields)) {
                $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
                curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
            }
            break;
        default:
            curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
            break;
    }
    $ssl = preg_match('/^https:\/\//i', $url) ? TRUE : FALSE;
    curl_setopt($ci, CURLOPT_URL, $url);
    if ($ssl) {
        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
        curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
    }
    //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
    curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量，这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
    curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ci, CURLINFO_HEADER_OUT, true);
    /*curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE带过去** */
    $response = curl_exec($ci);
    $requestinfo = curl_getinfo($ci);
    $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
    if ($debug) {
        echo "=====post data======\r\n";
        var_dump($postfields);
        echo "=====info===== \r\n";
        print_r($requestinfo);
        echo "=====response=====\r\n";
        print_r($response);
    }
    curl_close($ci);
    return $response;
    //return array($http_code, $response,$requestinfo);
}

/**
 * 过滤数组元素前后空格 (支持多维数组)
 * @param $array 要过滤的数组
 * @return array|string
 */
function trim_array_element($array){
    if(!is_array($array))
        return trim($array);
    return array_map('trim_array_element',$array);
}

/**
 * 检查手机号码格式
 * @param $mobile 手机号码
 */
function check_mobile($mobile){
    if(preg_match('/1[3456789]\d{9}$/',$mobile))
        return true;
    return false;
}

/**
 * 检查邮箱地址格式
 * @param $email 邮箱地址
 */
function check_email($email){
    if(filter_var($email,FILTER_VALIDATE_EMAIL))
        return true;
    return false;
}


/**
 *   实现中文字串截取无乱码的方法
 */
function getSubstr($string, $start, $length) {
    if(mb_strlen($string,'utf-8')>$length){
        $str = mb_substr($string, $start, $length,'utf-8');
        return $str.'...';
    }else{
        return $string;
    }
}


/**
 * 判断当前访问的用户是  PC端  还是 手机端  返回true 为手机端  false 为PC 端
 * @return boolean
 */
/**
　　* 是否移动端访问访问
　　*
　　* @return bool
　　*/
function isMobile()
{
    // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
        return true;

    // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
    if (isset ($_SERVER['HTTP_VIA']))
    {
        // 找不到为flase,否则为true
        return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
    }
    // 脑残法，判断手机发送的客户端标志,兼容性有待提高
    if (isset ($_SERVER['HTTP_USER_AGENT']))
    {
        $clientkeywords = array ('nokia','sony','ericsson','mot','samsung','htc','sgh','lg','sharp','sie-','philips','panasonic','alcatel','lenovo','iphone','ipod','blackberry','meizu','android','netfront','symbian','ucweb','windowsce','palm','operamini','operamobi','openwave','nexusone','cldc','midp','wap','mobile');
        // 从HTTP_USER_AGENT中查找手机浏览器的关键字
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT'])))
            return true;
    }
    // 协议法，因为有可能不准确，放到最后判断
    if (isset ($_SERVER['HTTP_ACCEPT']))
    {
        // 如果只支持wml并且不支持html那一定是移动设备
        // 如果支持wml和html但是wml在html之前则是移动设备
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html'))))
        {
            return true;
        }
    }
    return false;
}

function is_weixin() {
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
        return true;
    }
    return false;
}


function is_qq() {
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'QQ') !== false) {
        return true;
    } return false;
}
function is_alipay() {
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'AlipayClient') !== false) {
        return true;
    } return false;
}

//php获取中文字符拼音首字母
function getFirstCharter($str){
    if(empty($str))
    {
        return '';
    }
    $fchar=ord($str[0]);
    if($fchar>=ord('A')&&$fchar<=ord('z')) return strtoupper($str[0]);
    $s1=iconv('UTF-8','gb2312//TRANSLIT//IGNORE',$str);
    $s2=iconv('gb2312','UTF-8//TRANSLIT//IGNORE',$s1);
    $s=$s2==$str?$s1:$str;
    $asc=ord($s[0])*256+ord($s[1])-65536;
    if($asc>=-20319&&$asc<=-20284) return 'A';
    if($asc>=-20283&&$asc<=-19776) return 'B';
    if($asc>=-19775&&$asc<=-19219) return 'C';
    if($asc>=-19218&&$asc<=-18711) return 'D';
    if($asc>=-18710&&$asc<=-18527) return 'E';
    if($asc>=-18526&&$asc<=-18240) return 'F';
    if($asc>=-18239&&$asc<=-17923) return 'G';
    if($asc>=-17922&&$asc<=-17418) return 'H';
    if($asc>=-17417&&$asc<=-16475) return 'J';
    if($asc>=-16474&&$asc<=-16213) return 'K';
    if($asc>=-16212&&$asc<=-15641) return 'L';
    if($asc>=-15640&&$asc<=-15166) return 'M';
    if($asc>=-15165&&$asc<=-14923) return 'N';
    if($asc>=-14922&&$asc<=-14915) return 'O';
    if($asc>=-14914&&$asc<=-14631) return 'P';
    if($asc>=-14630&&$asc<=-14150) return 'Q';
    if($asc>=-14149&&$asc<=-14091) return 'R';
    if($asc>=-14090&&$asc<=-13319) return 'S';
    if($asc>=-13318&&$asc<=-12839) return 'T';
    if($asc>=-12838&&$asc<=-12557) return 'W';
    if($asc>=-12556&&$asc<=-11848) return 'X';
    if($asc>=-11847&&$asc<=-11056) return 'Y';
    if($asc>=-11055&&$asc<=-10247) return 'Z';
    return null;
}

/**
 * 获取整条字符串汉字拼音首字母
 * @param $zh
 * @return string
 */
function pinyin_long($zh){
    $ret = "";
    $s1 = iconv("UTF-8","gb2312", $zh);
    $s2 = iconv("gb2312","UTF-8", $s1);
    if($s2 == $zh){$zh = $s1;}
    for($i = 0; $i < strlen($zh); $i++){
        $s1 = substr($zh,$i,1);
        $p = ord($s1);
        if($p > 160){
            $s2 = substr($zh,$i++,2);
            $ret .= getFirstCharter($s2);
        }else{
            $ret .= $s1;
        }
    }
    return $ret;
}

function urlsafe_b64encode($string)
{
    $data = base64_encode($string);
    $data = str_replace(array('+','/','='),array('-','_',''),$data);
    return $data;
}

/**
 * 当前请求是否是https
 * @return type
 */
function is_https()
{
    return isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] && $_SERVER['HTTPS'] != 'off';
}
function mobile_hide($mobile){
    return substr_replace($mobile,'****',3,4);
}

/**
 * BMP 创建函数
 * @author simon
 * @param string $filename path of bmp file
 * @example who use,who knows
 * @return resource of GD
 */
if(!function_exists('imagecreatefrombmp')){
    function imagecreatefrombmp( $filename ){
        if ( !$f1 = fopen( $filename, "rb" ) )
            return FALSE;
        $FILE = unpack( "vfile_type/Vfile_size/Vreserved/Vbitmap_offset", fread( $f1, 14 ) );
        if ( $FILE['file_type'] != 19778 )
            return FALSE;
        $BMP = unpack( 'Vheader_size/Vwidth/Vheight/vplanes/vbits_per_pixel' . '/Vcompression/Vsize_bitmap/Vhoriz_resolution' . '/Vvert_resolution/Vcolors_used/Vcolors_important', fread( $f1, 40 ) );
        $BMP['colors'] = pow( 2, $BMP['bits_per_pixel'] );
        if ( $BMP['size_bitmap'] == 0 )
            $BMP['size_bitmap'] = $FILE['file_size'] - $FILE['bitmap_offset'];
        $BMP['bytes_per_pixel'] = $BMP['bits_per_pixel'] / 8;
        $BMP['bytes_per_pixel2'] = ceil( $BMP['bytes_per_pixel'] );
        $BMP['decal'] = ($BMP['width'] * $BMP['bytes_per_pixel'] / 4);
        $BMP['decal'] -= floor( $BMP['width'] * $BMP['bytes_per_pixel'] / 4 );
        $BMP['decal'] = 4 - (4 * $BMP['decal']);
        if ( $BMP['decal'] == 4 )
            $BMP['decal'] = 0;
        $PALETTE = array();
        if ( $BMP['colors'] < 16777216 ){
            $PALETTE = unpack( 'V' . $BMP['colors'], fread( $f1, $BMP['colors'] * 4 ) );
        }
        $IMG = fread( $f1, $BMP['size_bitmap'] );
        $VIDE = chr( 0 );
        $res = imagecreatetruecolor( $BMP['width'], $BMP['height'] );
        $P = 0;
        $Y = $BMP['height'] - 1;
        while( $Y >= 0 ){
            $X = 0;
            while( $X < $BMP['width'] ){
                if ( $BMP['bits_per_pixel'] == 32 ){
                    $COLOR = unpack( "V", substr( $IMG, $P, 3 ) );
                    $B = ord(substr($IMG, $P,1));
                    $G = ord(substr($IMG, $P+1,1));
                    $R = ord(substr($IMG, $P+2,1));
                    $color = imagecolorexact( $res, $R, $G, $B );
                    if ( $color == -1 )
                        $color = imagecolorallocate( $res, $R, $G, $B );
                    $COLOR[0] = $R*256*256+$G*256+$B;
                    $COLOR[1] = $color;
                }elseif ( $BMP['bits_per_pixel'] == 24 )
                    $COLOR = unpack( "V", substr( $IMG, $P, 3 ) . $VIDE );
                elseif ( $BMP['bits_per_pixel'] == 16 ){
                    $COLOR = unpack( "n", substr( $IMG, $P, 2 ) );
                    $COLOR[1] = $PALETTE[$COLOR[1] + 1];
                }elseif ( $BMP['bits_per_pixel'] == 8 ){
                    $COLOR = unpack( "n", $VIDE . substr( $IMG, $P, 1 ) );
                    $COLOR[1] = $PALETTE[$COLOR[1] + 1];
                }elseif ( $BMP['bits_per_pixel'] == 4 ){
                    $COLOR = unpack( "n", $VIDE . substr( $IMG, floor( $P ), 1 ) );
                    if ( ($P * 2) % 2 == 0 )
                        $COLOR[1] = ($COLOR[1] >> 4);
                    else
                        $COLOR[1] = ($COLOR[1] & 0x0F);
                    $COLOR[1] = $PALETTE[$COLOR[1] + 1];
                }elseif ( $BMP['bits_per_pixel'] == 1 ){
                    $COLOR = unpack( "n", $VIDE . substr( $IMG, floor( $P ), 1 ) );
                    if ( ($P * 8) % 8 == 0 )
                        $COLOR[1] = $COLOR[1] >> 7;
                    elseif ( ($P * 8) % 8 == 1 )
                        $COLOR[1] = ($COLOR[1] & 0x40) >> 6;
                    elseif ( ($P * 8) % 8 == 2 )
                        $COLOR[1] = ($COLOR[1] & 0x20) >> 5;
                    elseif ( ($P * 8) % 8 == 3 )
                        $COLOR[1] = ($COLOR[1] & 0x10) >> 4;
                    elseif ( ($P * 8) % 8 == 4 )
                        $COLOR[1] = ($COLOR[1] & 0x8) >> 3;
                    elseif ( ($P * 8) % 8 == 5 )
                        $COLOR[1] = ($COLOR[1] & 0x4) >> 2;
                    elseif ( ($P * 8) % 8 == 6 )
                        $COLOR[1] = ($COLOR[1] & 0x2) >> 1;
                    elseif ( ($P * 8) % 8 == 7 )
                        $COLOR[1] = ($COLOR[1] & 0x1);
                    $COLOR[1] = $PALETTE[$COLOR[1] + 1];
                }else
                    return FALSE;
                imagesetpixel( $res, $X, $Y, $COLOR[1] );
                $X++;
                $P += $BMP['bytes_per_pixel'];
            }
            $Y--;
            $P += $BMP['decal'];
        }
        fclose( $f1 );
        return $res;
    }
}

/**
 * 创建bmp格式图片
 *
 * @author: legend(legendsky@hotmail.com)
 * @link: http://www.ugia.cn/?p=96
 * @description: create Bitmap-File with GD library
 * @version: 0.1
 *
 * @param resource $im          图像资源
 * @param string   $filename    如果要另存为文件，请指定文件名，为空则直接在浏览器输出
 * @param integer  $bit         图像质量(1、4、8、16、24、32位)
 * @param integer  $compression 压缩方式，0为不压缩，1使用RLE8压缩算法进行压缩
 *
 * @return integer
 */
if(!function_exists('imagebmp')) {
    function imagebmp(&$im, $filename = '', $bit = 8, $compression = 0)
    {
        if (!in_array($bit, array(1, 4, 8, 16, 24, 32))) {
            $bit = 8;
        } else if ($bit == 32) // todo:32 bit
        {
            $bit = 24;
        }
        $bits = pow(2, $bit);
        // 调整调色板
        imagetruecolortopalette($im, true, $bits);
        $width = imagesx($im);
        $height = imagesy($im);
        $colors_num = imagecolorstotal($im);
        if ($bit <= 8) {
            // 颜色索引
            $rgb_quad = '';
            for ($i = 0; $i < $colors_num; $i++) {
                $colors = imagecolorsforindex($im, $i);
                $rgb_quad .= chr($colors['blue']) . chr($colors['green']) . chr($colors['red']) . "\0";
            }
            // 位图数据
            $bmp_data = '';
            // 非压缩
            if ($compression == 0 || $bit < 8) {
                if (!in_array($bit, array(1, 4, 8))) {
                    $bit = 8;
                }
                $compression = 0;
                // 每行字节数必须为4的倍数，补齐。
                $extra = '';
                $padding = 4 - ceil($width / (8 / $bit)) % 4;
                if ($padding % 4 != 0) {
                    $extra = str_repeat("\0", $padding);
                }
                for ($j = $height - 1; $j >= 0; $j--) {
                    $i = 0;
                    while ($i < $width) {
                        $bin = 0;
                        $limit = $width - $i < 8 / $bit ? (8 / $bit - $width + $i) * $bit : 0;
                        for ($k = 8 - $bit; $k >= $limit; $k -= $bit) {
                            $index = imagecolorat($im, $i, $j);
                            $bin |= $index << $k;
                            $i++;
                        }
                        $bmp_data .= chr($bin);
                    }
                    $bmp_data .= $extra;
                }
            } // RLE8 压缩
            else if ($compression == 1 && $bit == 8) {
                for ($j = $height - 1; $j >= 0; $j--) {
                    $last_index = "\0";
                    $same_num = 0;
                    for ($i = 0; $i <= $width; $i++) {
                        $index = imagecolorat($im, $i, $j);
                        if ($index !== $last_index || $same_num > 255) {
                            if ($same_num != 0) {
                                $bmp_data .= chr($same_num) . chr($last_index);
                            }
                            $last_index = $index;
                            $same_num = 1;
                        } else {
                            $same_num++;
                        }
                    }
                    $bmp_data .= "\0\0";
                }
                $bmp_data .= "\0\1";
            }
            $size_quad = strlen($rgb_quad);
            $size_data = strlen($bmp_data);
        } else {
            // 每行字节数必须为4的倍数，补齐。
            $extra = '';
            $padding = 4 - ($width * ($bit / 8)) % 4;
            if ($padding % 4 != 0) {
                $extra = str_repeat("\0", $padding);
            }
            // 位图数据
            $bmp_data = '';
            for ($j = $height - 1; $j >= 0; $j--) {
                for ($i = 0; $i < $width; $i++) {
                    $index = imagecolorat($im, $i, $j);
                    $colors = imagecolorsforindex($im, $index);
                    if ($bit == 16) {
                        $bin = 0 << $bit;
                        $bin |= ($colors['red'] >> 3) << 10;
                        $bin |= ($colors['green'] >> 3) << 5;
                        $bin |= $colors['blue'] >> 3;
                        $bmp_data .= pack("v", $bin);
                    } else {
                        $bmp_data .= pack("c*", $colors['blue'], $colors['green'], $colors['red']);
                    }
                    // todo: 32bit;
                }
                $bmp_data .= $extra;
            }
            $size_quad = 0;
            $size_data = strlen($bmp_data);
            $colors_num = 0;
        }
        // 位图文件头
        $file_header = "BM" . pack("V3", 54 + $size_quad + $size_data, 0, 54 + $size_quad);
        // 位图信息头
        $info_header = pack("V3v2V*", 0x28, $width, $height, 1, $bit, $compression, $size_data, 0, 0, $colors_num, 0);
        // 写入文件
        if ($filename != '') {
            $fp = fopen("test.bmp", "wb");
            fwrite($fp, $file_header);
            fwrite($fp, $info_header);
            fwrite($fp, $rgb_quad);
            fwrite($fp, $bmp_data);
            fclose($fp);
            return 1;
        }
        // 浏览器输出
        header("Content-Type: image/bmp");
        echo $file_header . $info_header;
        echo $rgb_quad;
        echo $bmp_data;
        return 1;
    }
}
/**
 * 	作用：array转xml
 */
function arrayToXml($arr)
{
    $xml = "<xml>";
    foreach ($arr as $key=>$val)
    {
        if (is_numeric($val))
        {
            $xml.="<".$key.">".$val."</".$key.">";

        }
        else
            $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
    }
    $xml.="</xml>";
    return $xml;
}

function verifyPwd($pwd){

//    if(strlen($pwd)<8) {
//        return ['msg'=>'长度最低8位'];
//    }
//
//    //字母数字
//    $pattern = '/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9a-zA-Z]+$/';
//    if(!preg_match($pattern,$pwd)){
//        return ['msg'=>'只能是数字加字母组合'];
//    }

    //去除一些常用弱口令
//    $ruo = array('123456','654321','123123','111111','888888','666666','000000','test');
//    foreach($ruo as $v){
//        if(strstr($pwd,$v)){
//            return ['msg'=>'不要使用常用弱口令，请更换'];
//        }
//    }

    return ['status'=>1];
}

//获取用户名
function getUsername(){
    $prefix = tpCache('userdata.u_prefix');
    $num = tpCache('userdata.u_randnum')?:6;
    $min = 1;
    for($i=1;$i<=$num;$i++){
        $min.="1";
    }

    $max = '';
    for($i=1;$i<=$num;$i++){
        $max.="9";
    }

    $rand = rand($min,$max);
    $username = $prefix.$rand;
    $have = Db::name('users')->where(['username'=>$username])->find();
    if(!$have){
        return $username;
    }else{
        return getUsername();
    }
}

function is_idcard( $id )
{
    $id = strtoupper($id);
    $regx = "/(^\d{15}$)|(^\d{17}([0-9]|X)$)/";
    $arr_split = array();
    if(!preg_match($regx, $id))
    {
        return FALSE;
    }
    if(15==strlen($id)) //检查15位
    {
        $regx = "/^(\d{6})+(\d{2})+(\d{2})+(\d{2})+(\d{3})$/";

        @preg_match($regx, $id, $arr_split);
        //检查生日日期是否正确
        $dtm_birth = "19".$arr_split[2] . '/' . $arr_split[3]. '/' .$arr_split[4];
        if(!strtotime($dtm_birth))
        {
            return FALSE;
        } else {
            return TRUE;
        }
    }
    else      //检查18位
    {
        $regx = "/^(\d{6})+(\d{4})+(\d{2})+(\d{2})+(\d{3})([0-9]|X)$/";
        @preg_match($regx, $id, $arr_split);
        $dtm_birth = $arr_split[2] . '/' . $arr_split[3]. '/' .$arr_split[4];
        if(!strtotime($dtm_birth)) //检查生日日期是否正确
        {
            return FALSE;
        }
        else
        {
            //检验18位身份证的校验码是否正确。
            //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
            $arr_int = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
            $arr_ch = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
            $sign = 0;
            for ( $i = 0; $i < 17; $i++ )
            {
                $b = (int) $id[$i];
                $w = $arr_int[$i];
                $sign += $b * $w;
            }
            $n = $sign % 11;
            $val_num = $arr_ch[$n];
            if ($val_num != substr($id,17, 1))
            {
                return FALSE;
            } //phpfensi.com
            else
            {
                return TRUE;
            }
        }
    }

}
function yc_phone($str){
    $str=$str;
    $resstr=substr_replace($str,'******',3,6);
    return $resstr;
}

/*
 * 时间判断--周几几点开始---周几几点结束
 */
function weekQujian($week1,$week2,$starttime,$endtime){
    $week = date('w');// "0" (星期日) 至 "6" (星期六)
    if($week==0) $week=7;
    $hour = date('G');// 如: "0" 至 "23"

    if($week1<$week2){
        for($i=$week1;$i<=$week2;$i++){
            $needweek[] = $i;
        }
    }else{//后台已经设定没有等于的情况
        //第一个的周期
        for($i=$week1;$i<=7;$i++){
            $needweek[] = $i;
        }
        //第二个的周期
        for($i=1;$i<=$week2;$i++){
            $needweek[] = $i;
        }
    }
    if(!in_array($week,$needweek)){
        return ['status'=>0,'msg'=>"周".$week1."--周".$week2."为开放时间"];
    }

    //在判断时间，只需要判断第一个周几的开始时间和最后周几的截止时间
    $first = array_shift($needweek);$end = array_pop($needweek);
    if($week==$first){
        if($hour<$starttime){
            return ['status'=>0,'msg'=>$starttime."点开始"];
        }
    }elseif($week==$end){
        if($hour>=$endtime){
            return ['status'=>0,'msg'=>"您来晚了，今日已经结束购买"];
        }
    }

    return ['status'=>1];
}

/**
 * 周几的上午几点--几点，下午几点--几点
 */
function timeQujian($week1,$time1,$time2,$time3,$time4){
    $week = date('w');// "0" (星期日) 至 "6" (星期六)
    if($week==0) $week=7;
    $hour = date('G');// 如: "0" 至 "23"

    //判断周几
    if($week!=$week1){
        return ['status'=>0,'msg'=>"周".$week1."为开放时间"];
    }

    //判断
    $timeary = [];
    for($i=$time1;$i<$time2;$i++){
        $timeary[] = $i;
    }
    for($i=$time3;$i<$time4;$i++){
        $timeary[] = $i;
    }
    if(!in_array($hour,$timeary)){
        return ['status'=>0,'msg'=>"上午".$time1."点-".$time2."点".",下午".$time3."点-".$time4."点为开放时间"];
    }

    return ['status'=>1];
}

/**
 * 取得下个周一
 * @internal param $time
 */
function getNextMonday()
{
    return strtotime('+1 week last monday');
}

/**
 * 获取零点
 */
function getLingdian($time=0){
    if($time==0) $time=time();
    return strtotime(date("Y-m-d"),$time);
}

/*
 * 获取地区列表
 */
function get_region_list(){
    return Db::name('region')->cache(true)->column('name','id');
}
/*
 * 获取用户地址列表
 */
function get_user_address_list($user_id){
    $lists = Db::name('user_address')->where(array('user_id'=>$user_id))->select();
    return $lists;
}
function getCurUrl(){
    $transport = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https' : 'http';
    $url = $transport.'://'.$_SERVER['HTTP_HOST'];
    return $url;
}

function getTglink($username){
    $url = getCurUrl();

    return $url."index.php/mobile/gongg/reg/tjr_id/".$username;
}

function getTgerweima($username){
    $url=getTglink($username);
    $fileName2="/public/upload/qrcode/".$username.'.png';
    GetQrcode($url,$level=3,$size=4,'.'.$fileName2);
    return $fileName2;
}

function getTgerweima2($username,$goods_id){
    $url = getCurUrl();
    $url .= "index.php/mobile/gongg/reg/tjr_id/".$username."/goods_id/".$goods_id;

    $fileName2="/public/upload/goods/".$username.$goods_id.'.png';
    GetQrcode($url,$level=3,$size=4,'.'.$fileName2);
    return $fileName2;
}

function GetQrcode($url='http://www.baidu.com',$level=3,$size=4,$fileName=false){
    vendor('phpqrcode.phpqrcode');
    $errorCorrectionLevel =intval($level) ;//容错级别
    $matrixPointSize = intval($size);//生成图片大小
    //生成二维码图片
    //echo $_SERVER['REQUEST_URI'];
    $object = new \QRcode();
    $object->png($url, $fileName, $errorCorrectionLevel, $matrixPointSize, 2);
}

function get_thum_images($goods_id,$original_img='', $width, $height,$type='goods')
{
    if (empty($goods_id)) return '';

    //判断缩略图是否存在
    $path = UPLOAD_PATH."$type/thumb/$goods_id/";
    $goods_thumb_name = "goods_thumb_{$goods_id}_{$width}_{$height}";

    // 这个商品 已经生成过这个比例的图片就直接返回了
    if (is_file($path . $goods_thumb_name . '.jpg')) return '/' . $path . $goods_thumb_name . '.jpg';
    if (is_file($path . $goods_thumb_name . '.jpeg')) return '/' . $path . $goods_thumb_name . '.jpeg';
    if (is_file($path . $goods_thumb_name . '.gif')) return '/' . $path . $goods_thumb_name . '.gif';
    if (is_file($path . $goods_thumb_name . '.png')) return '/' . $path . $goods_thumb_name . '.png';

    if (empty($original_img)) {
        return '/public/images/icon_goods_thumb_empty_300.png';
    }

    $ossClient = new \app\common\logic\OssLogic;
    if (($ossUrl = $ossClient->getGoodsThumbImageUrl($original_img, $width, $height))) {
        return $ossUrl;
    }

    $original_img = '.' . $original_img; // 相对路径
    if (!is_file($original_img)) {
        return '/public/images/icon_goods_thumb_empty_300.png';
    }

    try {
        require_once 'vendor/topthink/think-image/src/Image.php';
        require_once 'vendor/topthink/think-image/src/image/Exception.php';
        if(strstr(strtolower($original_img),'.gif'))
        {
            require_once 'vendor/topthink/think-image/src/image/gif/Encoder.php';
            require_once 'vendor/topthink/think-image/src/image/gif/Decoder.php';
            require_once 'vendor/topthink/think-image/src/image/gif/Gif.php';
        }
        $image = \think\Image::open($original_img);

        $goods_thumb_name = $goods_thumb_name . '.' . $image->type();
        // 生成缩略图
        !is_dir($path) && mkdir($path, 0777, true);
        // 参考文章 http://www.mb5u.com/biancheng/php/php_84533.html  改动参考 http://www.thinkphp.cn/topic/13542.html
        $image->thumb($width, $height, 1)->save($path . $goods_thumb_name, NULL, 100); //按照原图的比例生成一个最大为$width*$height的缩略图并保存
        $img_url = '/' . $path . $goods_thumb_name;

        return $img_url;
    } catch (think\Exception $e) {

        return $original_img;
    }
}

/**
 *  商品缩略图 给于标签调用 拿出商品表的 original_img 原始图来裁切出来的
 * @param type $goods_id  商品id
 * @param type $width     生成缩略图的宽度
 * @param type $height    生成缩略图的高度
 */
function goods_thum_images($goods_id, $width, $height)
{
    ini_set('memory_limit','200M');
    if (empty($goods_id)) return '';

    //判断缩略图是否存在
    $path = UPLOAD_PATH."goods/thumb/$goods_id/";
    $goods_thumb_name = "goods_thumb_{$goods_id}_{$width}_{$height}";

    // 这个商品 已经生成过这个比例的图片就直接返回了
    if (is_file($path . $goods_thumb_name . '.jpg')) return '/' . $path . $goods_thumb_name . '.jpg';
    if (is_file($path . $goods_thumb_name . '.jpeg')) return '/' . $path . $goods_thumb_name . '.jpeg';
    if (is_file($path . $goods_thumb_name . '.gif')) return '/' . $path . $goods_thumb_name . '.gif';
    if (is_file($path . $goods_thumb_name . '.png')) return '/' . $path . $goods_thumb_name . '.png';
    $original_img = Db::name('goods')->where("goods_id", $goods_id)->cache(true, 30, 'original_img_cache')->value('original_img');
    $original_img= trim($original_img,'/');
    if(!file_exists($original_img)){
        $original_img = Db::name('GoodsImages')->where("goods_id = $goods_id")->order('img_id asc')->value('image_url');

    }
    if (empty($original_img)) {
        return '/public/images/icon_goods_thumb_empty_300.png';
    }

//    $ossClient = new \app\common\logic\OssLogic;
//    if (($ossUrl = $ossClient->getGoodsThumbImageUrl($original_img, $width, $height))) {
//        return $ossUrl;
//    }

    $original_img =ROOT_PATH . $original_img; // 相对路径
    if (!is_file($original_img)) {
        return '/public/images/icon_goods_thumb_empty_300.png';
    }

    try {
        require_once 'vendor/topthink/think-image/src/Image.php';
        require_once 'vendor/topthink/think-image/src/image/Exception.php';
        if(strstr(strtolower($original_img),'.gif'))
        {
            require_once 'vendor/topthink/think-image/src/image/gif/Encoder.php';
            require_once 'vendor/topthink/think-image/src/image/gif/Decoder.php';
            require_once 'vendor/topthink/think-image/src/image/gif/Gif.php';
        }
        $image = \think\Image::open($original_img);

        $goods_thumb_name = $goods_thumb_name . '.' . $image->type();
        // 生成缩略图
        !is_dir($path) && mkdir($path, 0777, true);
        // 参考文章 http://www.mb5u.com/biancheng/php/php_84533.html  改动参考 http://www.thinkphp.cn/topic/13542.html
        $image->thumb($width, $height, 1)->save($path . $goods_thumb_name, NULL, 100); //按照原图的比例生成一个最大为$width*$height的缩略图并保存
        $img_url = '/' . $path . $goods_thumb_name;

        return $img_url;
    } catch (think\Exception $e) {

        return $original_img;
    }
}

/**
 * 商品相册缩略图
 */
function get_sub_images($sub_img, $goods_id, $width, $height)
{
    //判断缩略图是否存在
    $path = UPLOAD_PATH."goods/thumb/$goods_id/";
    $goods_thumb_name = "goods_sub_thumb_{$sub_img['img_id']}_{$width}_{$height}";

    //这个缩略图 已经生成过这个比例的图片就直接返回了
    if (is_file($path . $goods_thumb_name . '.jpg')) return '/' . $path . $goods_thumb_name . '.jpg';
    if (is_file($path . $goods_thumb_name . '.jpeg')) return '/' . $path . $goods_thumb_name . '.jpeg';
    if (is_file($path . $goods_thumb_name . '.gif')) return '/' . $path . $goods_thumb_name . '.gif';
    if (is_file($path . $goods_thumb_name . '.png')) return '/' . $path . $goods_thumb_name . '.png';

    $ossClient = new \app\common\logic\OssLogic;
    if (($ossUrl = $ossClient->getGoodsAlbumThumbUrl($sub_img['image_url'], $width, $height))) {
        return $ossUrl;
    }

    $original_img = '.' . $sub_img['image_url']; //相对路径
    if (!is_file($original_img)) {
        return '/public/images/icon_goods_thumb_empty_300.png';
    }

    try {
        require_once 'vendor/topthink/think-image/src/Image.php';
        require_once 'vendor/topthink/think-image/src/image/Exception.php';
        if(strstr(strtolower($original_img),'.gif'))
        {
            require_once 'vendor/topthink/think-image/src/image/gif/Encoder.php';
            require_once 'vendor/topthink/think-image/src/image/gif/Decoder.php';
            require_once 'vendor/topthink/think-image/src/image/gif/Gif.php';
        }
        $image = \think\Image::open($original_img);

        $goods_thumb_name = $goods_thumb_name . '.' . $image->type();
        // 生成缩略图
        !is_dir($path) && mkdir($path, 0777, true);
        // 参考文章 http://www.mb5u.com/biancheng/php/php_84533.html  改动参考 http://www.thinkphp.cn/topic/13542.html
        $image->thumb($width, $height, 2)->save($path . $goods_thumb_name, NULL, 100); //按照原图的比例生成一个最大为$width*$height的缩略图并保存
        $img_url = '/' . $path . $goods_thumb_name;

        return $img_url;
    } catch (think\Exception $e) {

        return $original_img;
    }
}

/**
 * 查询快递
 * @param $postcom  快递公司编码
 * @param $getNu  快递单号
 * @return array  物流跟踪信息数组
 */
function queryExpress($postcom , $getNu) {
    $url = "https://m.kuaidi100.com/query?type=".$postcom."&postid=".$getNu."&id=1&valicode=&temp=0.49738534969422676";
    $resp = httpRequest($url,"GET");
    return json_decode($resp,true);
}

/**
 * 获取缓存或者更新缓存
 * @param string $config_key 缓存文件名称
 * @param array $data 缓存数据  array('k1'=>'v1','k2'=>'v3')
 * @return array or string or bool
 */
function tpCache($config_key,$data = array()){
    $param = explode('.', $config_key);
    if(empty($data)){
        //如$config_key=shop_info则获取网站信息数组
        //如$config_key=shop_info.logo则获取网站logo字符串
        $config = cache($param[0]);//直接获取缓存文件

        if(empty($config)){
            //缓存文件不存在就读取数据库
            $res = Db::name('config')->where("inc_type",$param[0])->order('sort asc,id asc')->select();
            if($res){
                foreach($res as $k=>$val){
                    if(strstr($val['value'],'a:')){
                        $config[$val['name']] =unserialize($val['value']);
                    }else{
                        $config[$val['name']] = $val['value'];
                    }
                }
                cache($param[0],$config);
            }
        }
        if(count($param)>1){
            return $config[$param[1]]??0;
        }else{
            return $config;
        }
    }else{
        $olddata=$data;
        //数组序列化
        foreach($data as $k=>$v){
            if(is_array($v)){
                $data[$k] = serialize($v);
            }
        }
        //更新缓存
        $result =  Db::name('config')->where("inc_type", $param[0])->select();
        if($result){
            foreach($result as $val){
                $temp[$val['name']] = $val['value'];
            }
            foreach ($data as $k=>$v){
                $newArr = array('name'=>$k,'value'=>trim($v),'inc_type'=>$param[0]);
                if(!isset($temp[$k])){
                    Db::name('config')->insert($newArr);//新key数据插入数据库
                }else{
                    if($v!=$temp[$k])
                        Db::name('config')->where("name", $k)->update($newArr);//缓存key存在且值有变更新此项
                }
            }
            //更新后的数据库记录
            $newRes = Db::name('config')->where("inc_type", $param[0])->select();
            foreach ($newRes as $rs){
                if(strstr($rs['value'],'a:')){
                    $rs['value'] = unserialize($rs['value']);
                }
                $newData[$rs['name']] = $rs['value'];
            }
        }else{
            foreach($data as $k=>$v){
                $newArr[] = array('name'=>$k,'value'=>trim($v),'inc_type'=>$param[0]);
            }
            Db::name('config')->insertAll($newArr);
            $newData = $olddata;
        }
        return cache($param[0],$newData);
    }
}
/**
 * 开关
 */
function open($key){
    return tpCache('open.'.$key);
}

//金额操作和日志记录
function qianbao($userid,$money,$type,$action,$desc='',$periods_id=0,$money_type=0)
{
    $result['status']=false;
    $result['msg']='';
    //获取
    $money = floatval( $money );
    if( $money == 0 )
    {
        $result['msg'] = '1-交易金额为0';
        return $result;
    }
    $user = Db::name('wallet')->lock(true)->where(array('user_id'=>$userid))->find();
    //检测
    if( !$user)
    {
        $result['msg'] = '2-用户帐号不存在';
        return $result;
    }
    if(($user[$type]+$money)<0 && $money<0)
    {
        $result['msg']='3-账户余额不足';
    }else{
        $retule=Db::name('wallet')->where('id',$user['id'])->inc($type,$money)->update();
        if($retule)
        {
            $curtime = getCurTime();
            $data = [];
            $data['user_id']=$userid;
            $data['money']=$money;
            $data['yue']=$user[$type]+$money;
            $data['action']=$action;
            $data['desc']=$desc;
            $data['w_time']=$curtime;
            $data['type'] = $money_type;
            if($type=='yuqi' || $type=='shouyi' || $type=='score'  || $type=='baodan1'  || $type=='baodan2'   || $type=='shouyi2' ){
                $data['periods_id'] = $periods_id;
            }
            $rs =Db::name($type.'_log')->insert($data);
            if(!$rs){
                $result['msg']='4-添加财务明细失败';
                return $result;
            }
        }else{
            $result['msg']='5-更新余额失败';
            return $result;
        }
        $result['status']=true;
    }
    return $result;
}

//金额操作和日志记录
function qianbao_supply($userid,$money,$type,$action,$desc='',$periods_id=0,$money_type=0)
{
    $result['status']=false;
    $result['msg']='';
    //获取
    $money = floatval( $money );
    if( $money == 0 )
    {
        $result['msg'] = '1-交易金额为0';
        return $result;
    }
    $user = Db::name('suppliers')->lock(true)->where(array('id'=>$userid))->find();
    //检测
    if( !$user)
    {
        $result['msg'] = '2-用户帐号不存在';
        return $result;
    }
    if(($user[$type]+$money)<0 && $money<0)
    {
        $result['msg']='3-账户余额不足';
    }else{
        $score_data = array($type=>array('exp','`'.$type.'`+'.$money));
        $retule=Db::name('suppliers')->where(array('id'=>$user['id']))->update($score_data);
        if($retule)
        {
            $curtime = getCurTime();
            $data = [];
            $data['user_id']=$userid;
            $data['money']=$money;
            $data['yue']=$user[$type]+$money;
            $data['action']=$action;
            $data['desc']=$desc;
            $data['w_time']=$curtime;
            $data['type'] = $money_type;
            $rs =Db::name($type.'_log')->add($data);
            if(!$rs){
                $result['msg']='4-添加财务明细失败';
                return $result;
            }
        }else{
            $result['msg']='5-更新余额失败';
            return $result;
        }
        $result['status']=true;
    }
    return $result;
}
/**
 * 写入静态页面缓存
 */
function write_html_cache($html){
    $html_cache_arr = C('HTML_CACHE_ARR');
    $request = think\Request::instance();
    $m_c_a_str = $request->module().'_'.$request->controller().'_'.$request->action(); // 模块_控制器_方法
    $m_c_a_str = strtolower($m_c_a_str);
    //exit('write_html_cache写入缓存<br/>');
    foreach($html_cache_arr as $key=>$val)
    {
        $val['mca'] = strtolower($val['mca']);
        if($val['mca'] != $m_c_a_str) //不是当前 模块 控制器 方法 直接跳过
            continue;

        //if(!is_dir(RUNTIME_PATH.'html'))
        //mkdir(RUNTIME_PATH.'html');
        //$filename =  RUNTIME_PATH.'html'.DIRECTORY_SEPARATOR.$m_c_a_str;
        $filename =  $m_c_a_str;
        // 组合参数
        if(isset($val['p']))
        {
            foreach($val['p'] as $k=>$v)
                $filename.='_'.$_GET[$v];
        }
        $filename.= '.html';
        \think\Cache::set($filename,$html);
        //file_put_contents($filename, $html);
    }
}

/**
 * 读取静态页面缓存
 */
function read_html_cache(){
    $html_cache_arr = C('HTML_CACHE_ARR');
    $request = think\Request::instance();
    $m_c_a_str = $request->module().'_'.$request->controller().'_'.$request->action(); // 模块_控制器_方法
    $m_c_a_str = strtolower($m_c_a_str);
    //exit('read_html_cache读取缓存<br/>');
    foreach($html_cache_arr as $key=>$val)
    {
        $val['mca'] = strtolower($val['mca']);
        if($val['mca'] != $m_c_a_str) //不是当前 模块 控制器 方法 直接跳过
            continue;

        //$filename =  RUNTIME_PATH.'html'.DIRECTORY_SEPARATOR.$m_c_a_str;
        $filename =  $m_c_a_str;
        // 组合参数
        if(isset($val['p']))
        {
            foreach($val['p'] as $k=>$v)
                $filename.='_'.$_GET[$v];
        }
        $filename.= '.html';
        $html = \think\Cache::get($filename);
        if($html)
        {
            //echo file_get_contents($filename);
            echo \think\Cache::get($filename);
            exit();
        }
    }
}


//获取当前时间
function getCurTime(){
    $time = time();
    //读取后台系统参数，仅用于测试，正式时，需要清空，并隐藏
    $test_time = tpCache('bonus.test_time');
    if($test_time>0){
        $time += ($test_time*86400);
    }
    return $time;
}

function t($text){
    return $text;
}
function getplatformname($pl){
    return $pl;
}
//获取编辑器的内容
function geteditorcontent($content){
    $contentArr = json_decode(htmlspecialchars_decode($content), true);
    if(!$contentArr){
        $content = preg_replace_callback('/(<img.*?src=[\'|\"])([^\"\']*?)([\'|\"].*?[\/]?>)/is', function($matches){
            dump($matches);exit;
            //dump(trim(str_replace('&quot;','',$matches[2])));die;
            //$rurl = \app\common\Pic::uploadoss(trim(str_replace('&quot;','',$matches[2])));
            //return $matches[1].$rurl.$matches[3];
        }, $content);


        return $content;
    }
    $content = jsonEncode($contentArr);
    return $content;
}
function getdomain(){
    $transport = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https' : 'http';
    $url = $transport.'://'.$_SERVER['HTTP_HOST'].'/';
    return $url;
}

function m_url($url){
    $pre_url = rtrim(getdomain(),'/');
    return $pre_url.'/h5/index.html#/'.ltrim($url,'/');
}

//curl post请求
function curl_post($url, $keysArr=array(), $flag = 0,$headers=array()){
    $ch = curl_init();
    if(! $flag) curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $keysArr);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    if($headers){
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }
    try {
        $response = curl_exec($ch);
    } catch (\Exception $e) {
        return null;
    }
    $curlError = curl_error($ch);
    if(!empty($curlError)) {
        return null;
    }
    curl_close($ch);
    //-------请求为空
    if(empty($response)){
        return null;
    }
    return $response;
}
//写日志
function writeLog($content='',$log_name=''){
    if(empty($content)){
        return true;
    }
    if(empty($log_name)){
        $log_name = date('Y-m-d').'log.log';
    }else{
        $log_name =$log_name.date('Y-m-d').'.log';
    }
    $log_pth = ROOT_PATH.'runtime'.DS.'log'.DS;
    if(!file_exists($log_pth)){
        mkdir($log_pth,0775,true);
    }
    file_put_contents($log_pth.$log_name,date('Y-m-d H:i:s').'::'.$content."\r\n",FILE_APPEND);
    return true;
}

function platform()
{
    $platform='h5';
    $a_strtolower = strtolower($_SERVER['HTTP_USER_AGENT']);
    if(strpos($a_strtolower, "micromessenger"))//公众号MicroMessenger
    {
        if(strpos($a_strtolower, "miniprogram"))//小程序
        {
            $platform = 'wx_app';
        } else if(input('platform')=='wx'){
            $platform = 'wx_app';
        }else{
            $platform = 'wx';
        }
    }
    elseif(strpos($a_strtolower, "uni-app") || strpos($a_strtolower, "Html5Plus"))//app
    {
        $platform = 'app';
    }
    return $platform;
}

//导出excel
function export_excel(array $titleArr,array $dataArr,array $typeArr=[],$file_name=''){
    $phpexcel = new \PhpOffice\PhpSpreadsheet\Spreadsheet();//实例化
    $phpsheet = $phpexcel->getActiveSheet();
    //填充表头信息
    $widthArr = [];
    for($i = 0;$i < count($titleArr);$i++) {
        $phpsheet->setCellValue(IntToChr($i)."1","$titleArr[$i]");
        $widthArr[] = strlen($titleArr[$i]);
    }
    //填充表格信息
    for ($i = 2;$i <= count($dataArr) + 1;$i++) {
        $j = 0;
        foreach ($dataArr[$i-2] as $key=>$value) {
            if($typeArr && $typeArr[$j] == 1)//数字
                $phpsheet->setCellValue(IntToChr($j)."$i","$value");
            else
                $phpsheet->setCellValueExplicit(IntToChr($j)."$i","$value",\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
            if(strlen($value) > $widthArr[$j]){
                $widthArr[$j] = strlen($value);
                if($widthArr[$j] > 25) $widthArr[$j] = 25;
            }
            $j++;
        }
    }
    //设置列宽
    foreach($widthArr as $k=>$v){
        $phpsheet->getColumnDimension(IntToChr($k))->setWidth($v+2);
    }
    $phpwriter = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($phpexcel,"Xlsx");
    if(!$file_name){
        $file_name = date('YmdHis').rand(1000,9999).'.xlsx';
    }
    if(!file_exists(ROOT_PATH.'runtime/excel/')){
        mkdir(ROOT_PATH.'runtime/excel/',0775,true);
    }
    $save_file =  ROOT_PATH.'runtime/excel/'.$file_name;
    $phpwriter->save($save_file);
    $domain_url = getCurUrl();
    return $domain_url.'/runtime/excel/'.$file_name;
}
//导出复杂excel
function export_excel_complex($dataArr,$title_arr,$foot_arr,$file_name='',$img_path=''){
    $phpexcel = new \PhpOffice\PhpSpreadsheet\Spreadsheet();//实例化
    $phpsheet = $phpexcel->getActiveSheet();
    $titleArr = [];
    //1、处理总标题
    $title_count = 1;
    foreach($title_arr as $title_k=>$title_v){
        $chr_i = $title_k+1;
        if($title_v['type']==1){
            $titleArr = $title_v['title'];
            continue;
        }else{
            $title_count++;
            $merage_set = $title_v['merage_set'];
            $style_arr = $title_v['style_arr'];
            $start_i = 0;
            foreach($title_v['title'] as $tk=>$tv){
                $start_chr = IntToChr($start_i);
                if($merage_set[$tk]){
                    $end_chr = IntToChr($start_i+$merage_set[$tk]-1);
                    //dump($start_i.'=>'.bcadd($start_i,$merage_set[$tk]-1).'合并'.$start_chr.$chr_i.':'.$end_chr.$chr_i);
                    $phpsheet->mergeCells($start_chr.$chr_i.':'.$end_chr.$chr_i);
                    $start_i = $start_i + $merage_set[$tk];
                }
                //dump('内容'.$start_chr.$chr_i.'=>'.$tv);
                $phpsheet->setCellValue($start_chr.$chr_i,$tv);
                if($style_arr){
                    $phpsheet->getStyle($start_chr.$chr_i)->applyFromArray($style_arr);
                }
            }
        }
    }
    //die('stop');

    //2、填充正常表格
    //$titleArr = ['序号','品牌','商品名称','规格型号','单位','数量','单价','金额','备注'];
    $typeArr = [];
    $start_cos = $title_count;
    //填充表头信息
    $widthArr = [];
    for($i = 0;$i < count($titleArr)+1;$i++) {
        $phpsheet->setCellValue(IntToChr($i).$start_cos,"$titleArr[$i]");
        $widthArr[] = strlen($titleArr[$i]);
    }

    //填充表格信息
    for ($i = 2;$i <= count($dataArr) + 1;$i++) {
        $start_cos++;
        $j = 0;
        foreach ($dataArr[$i-2] as $key=>$value) {
            if($typeArr && $typeArr[$j] == 1)//数字
                $phpsheet->setCellValue(IntToChr($j)."$start_cos","$value");
            else
                $phpsheet->setCellValueExplicit(IntToChr($j)."$start_cos","$value",\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
            if(strlen($value) > $widthArr[$j]){
                $widthArr[$j] = strlen($value);
                if($widthArr[$j] > 25) $widthArr[$j] = 25;
            }
            $j++;
        }
    }
    if($img_path){
        $img_cos = $start_cos+1;
        $column = count($titleArr)-1;
        $img_path = \app\common\Pic::tolocal($img_path);
        $img_path = str_replace(PRE_URL,ROOT_PATH,$img_path);
        // $phpsheet->mergeCells(IntToChr(0).$img_cos.':'.IntToChr($column).$img_cos);
        //$phpsheet->getColumnDimension(IntToChr($column))->setWidth(150);

        // $phpsheet->getRowDimension($img_cos)->setRowHeight(150);
        //dump(IntToChr($column));exit;
        //dump(IntToChr(0).$img_cos.':'.IntToChr($column).$img_cos);exit;
        //添加图片
        //dump(IntToChr($column).$img_cos);exit;
        $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
        $drawing->setName($img_path);
        $drawing->setDescription('Image inserted by PhpSpreadsheet');
        $drawing->setPath($img_path);
        $drawing->setCoordinates(IntToChr(0).$img_cos);
        $drawing->setOffsetX($img_cos);
        $drawing->setOffsetY($column*2);
        $drawing->setWidthAndHeight(150, 150);
        $drawing->setResizeProportional(true);
        //$drawing->setMimeType(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_GENERAL);
        $drawing->setWorksheet($phpsheet);
    }
    //设置列宽
    foreach($widthArr as $k=>$v){
        $phpsheet->getColumnDimension(IntToChr($k))->setWidth($v+2);
    }
    $phpwriter = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($phpexcel,"Xlsx");
    if(!$file_name){
        $file_name = date('YmdHis').rand(1000,9999).'.xlsx';
    }
    if(!file_exists(ROOT_PATH.'runtime/excel/')){
        mkdir(ROOT_PATH.'runtime/excel/',775,true);
    }
    $save_file =  ROOT_PATH.'runtime/excel/'.$file_name;
    $phpwriter->save($save_file);
    return PRE_URL.'/runtime/excel/'.$file_name;
}

//excel转pdf
function send_order_pdf($file,$name){
    $file = ROOT_PATH.'runtime/excel/send_order.xlsx';
    $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReaderForFile($file);
    $phpWord = $reader->load($file);
    $phpWord ->getDefaultStyle()->applyFromArray(
        [
            // 字体
            'font'=>[
                'name' => 'Arial',
                'bold' => true,
                'italic' => false,
                'underline' => \PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_DOUBLE,
                'strikethrough' => false,
                'color' => [
                    'rgb' => '808080'
                ]
            ],
            // 边框
            'borders' => [
                'allBorders' => [
                    'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
                ]
            ],
            'alignment' => [
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
                'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
                'wrapText' => true,
            ],
            'quotePrefix'    => true,
            'mode'=>'utf-8',
            'format'=>'A4',
            'useSubstitutions'=>true,
            'useAdobeCJK'=>true,
            'autoScriptToLang'=>true,
            'autoLangToFont'=>true,
            'mgl'=>15,
            'mgr'=>15,
            'mgt'=>16,
            'mgb'=>16,
            'mgh'=>9,
            'mgf'=>9,
            'orientation'=>'P'
        ]
    );
    $xmlWriter = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($phpWord,'Mpdf');
    $xmlWriter->writeAllSheets();
    $name = '123.pdf';
    $path = ROOT_PATH.'runtime/excel/';
    $xmlWriter->save($path.'\\'.$name);

    return PRE_URL.'runtime/excel/'.$name;
}

function request_get($url, $keysArr=array(), $timeout = 30){
    $client = new \GuzzleHttp\Client(['timeout'=>$timeout,'verify'=>false]);
    try {
        if($keysArr){
            $response = $client->request('GET',$url,['query'=>$keysArr]);
        }else{
            $response = $client->request('GET',$url);
        }
        $rs = $response->getBody()->getContents();
    } catch(\Throwable $e){
        //\think\facade\Log::write($e->getMessage());
        var_dump($e->getMessage());
    }
    return $rs;
}
//生成二维码
function createqrcode($url,$logo=''){
    $qrCode=new \Endroid\QrCode\QrCode();
    $qrCode->setText($url);
    $qrCode->setSize(300);
    $qrCode->setForegroundColor(array('r' => 0, 'g' => 0, 'b' => 0, 'a' => 0));
    $qrCode->setBackgroundColor(array('r' => 255, 'g' => 255, 'b' => 255, 'a' => 0));
    $qrCode->setLabelFontSize(16);
    if($logo){
        $qrCode->setLogoPath($logo);
        $qrCode->setLogoSize(80);
    }
    $url = '/upload/qrcode/'.date('Ym/d_His').rand(10000000,99999999).'.jpg';
    $file = ROOT_PATH.ltrim($url,'/');
    if(!is_dir(dirname($file))){
        @mkdir(dirname($file),0777,true);
    }else{
        if(file_exists($file)){
            $url = '/upload/qrcode/'.date('Ym/d_His').rand(10000000,99999999).'.jpg';
            $file = ROOT_PATH.ltrim($url,'/');
        }
    }
    $qrCode->writeFile($file);
    $domain_url = getCurUrl();
    return $domain_url.$url;
}

if (!function_exists('random')) {
    function random($length, $numeric = false) {
        $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
        $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
        if ($numeric) {
            $hash = '';
        } else {
            $hash = chr(rand(1, 26) + rand(0, 1) * 32 + 64);
            --$length;
        }
        $max = strlen($seed) - 1;
        for ($i = 0; $i < $length; ++$i) {
            $hash .= $seed[mt_rand(0, $max)];
        }

        return $hash;
    }
}
if (!function_exists('IntToChr')) {
    function IntToChr($index, $start = 65) {
        $str = '';
        if (floor($index / 26) > 0) {
            $str .= IntToChr(floor($index / 26)-1);
        }
        return $str . chr($index % 26 + $start);
    }
}
if (!function_exists('M')) {
    /**
     * 采有TP5最新助手函数特性实现函数简写方式 M
     * @param string $name 表名
     * @return DB对象
     */
    function M($name = '')
    {
        if(!empty($name))
        {
            return Db::name($name);
        }
    }
}

function model($table){
    $table_name = convert_underscore_to_camelcase($table);
    $modelClass = 'app\\common\\model\\'. $table_name;
    $model = new $modelClass();
    return $model;
}

function convert_underscore_to_camelcase($string) {
    $parts = explode('_', $string);
    foreach ($parts as $index => $part) {
        $parts[$index] = ucfirst($part);
    }
    $camelCaseString = implode('', $parts);
    return $camelCaseString;
}

function getdistance($lng1, $lat1, $lng2, $lat2, $len_type = 1, $decimal = 2){
    $radLat1 = $lat1 * PI()/ 180.0;   //PI()圆周率
    $radLat2 = $lat2 * PI() / 180.0;
    $a = $radLat1 - $radLat2;
    $b = ($lng1 * PI() / 180.0) - ($lng2 * PI() / 180.0);
    $s = 2 * asin(sqrt(pow(sin($a/2),2) + cos($radLat1) * cos($radLat2) * pow(sin($b/2),2)));
    $s = $s * 6378.137;
    $s = round($s * 1000);
    if ($len_type --> 1) {
        $s /= 1000;
    }
    return round($s, $decimal);
}

function getplugins($code=null){
    //根据插件标识判断是否有该插件
    if(file_exists(ROOT_PATH.'plugins.php')){
        $plugins = include(ROOT_PATH.'plugins.php');
    }
    if(!$code) return $plugins;
    $exit = in_array($code,$plugins);
    return $exit;
}